let webSocket:WebSocket ;
let socketOpen = false;

// 发送消息
export const doSend = (message) => {
    if (socketOpen&& webSocket!==null) {
        webSocket.send(message)
    }
}

export const colse = () => {
    if (socketOpen&& webSocket!==null) {
        webSocket.close()
    }
}

export const pong=()=>{
    setInterval(()=>{
        if (socketOpen && webSocket!==null){
            webSocket.send("pong..")
        }
    },2000)
}

// 初始化websocket
export const contactSocket = (receive:Function) => {
    if ("WebSocket" in window) {
        webSocket = new WebSocket("ws://127.0.0.1:2024/public/ws");
        webSocket.onopen = function () {
            console.log("连接成功！");
            socketOpen = true
        };
        webSocket.onmessage = function (evt) {
            let message:string = evt.data;
        };
        webSocket.onclose = function () {
            socketOpen=false
            console.log("连接关闭！");
        };
        webSocket.onerror = function () {
            console.log("连接异常！");
        };
    }
}
